<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name"
                placeholder="输入查询名称"
                style="width: 200px; margin-right: 20px; "
                class="filter-item"
                @keyup.enter.native="handleFilter" />
      <el-button v-waves
                 class="filter-item"
                 type="primary"
                 icon="el-icon-search"
                 size="small"
                 @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item"
                 style="margin-left: 10px;"
                 type="primary"
                 icon="el-icon-plus"
                 size="small"
                 @click="handleCreate">
        新增
      </el-button>
    </div>
    </br>
    <!--全局配置列表    -->
    <el-table :key="tableKey"
              v-loading="listLoading"
              :data="list"
              border
              fit
              highlight-current-row
              style="width: 100%;"
              @sort-change="sortChange">
      <el-table-column type="index"
                       align="center"
                       label="#" />
      <el-table-column label="名称"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="作者"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.author }}</span>
        </template>
      </el-table-column>
      <el-table-column label="注释日期"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.commentDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="输出目录"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.outputDir }}</span>
        </template>
      </el-table-column>
      <el-table-column label="时间策略"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.dateType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="禁止打开输出目录"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.disableOpenDir| yesOrNoFilter(row.disableOpenDir) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="覆盖已生成文件"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.fileOverride | yesOrNoFilter(row.fileOverride) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开启lombok模式"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.lombok | yesOrNoFilter(row.lombok) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开启swagger模式"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.swagger | yesOrNoFilter(row.swagger) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开启kotlin模式"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.kotlin | yesOrNoFilter(row.kotlin) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作"
                       align="center"
                       class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary"
                     size="mini"
                     @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'"
                     size="mini"
                     type="danger"
                     @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页插件 -->
    <pagination v-show="total>0"
                :total="total"
                :page.sync="listQuery.pageNo"
                :limit.sync="listQuery.pageSize"
                @pagination="getList" />
    <!--编辑和新增的表单 -->
    <el-dialog :title="textMap[dialogStatus]"
               :visible.sync="dialogFormVisible">
      <el-form ref="dataForm"
               :rules="rules"
               :model="temp"
               label-position="left"
               label-width="150px"
               inline
               style="width: 400px; margin-left:50px;">
        <el-form-item label="名称"
                      prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="作者"
                      prop="author">
          <el-input v-model="temp.author" />
        </el-form-item>
        <el-form-item label="输出目录"
                      prop="outputDir">
          <el-input v-model="temp.outputDir" />
        </el-form-item>
        <el-form-item label="时间策略"
                      prop="dateType">
          <el-select v-model="temp.dateType"
                     placeholder="请选择"
                     size="small">
            <el-option v-for="item in dateTypeOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="注释日期"
                      prop="commentDate">
          <el-select v-model="temp.commentDate"
                     placeholder="请选择"
                     size="small">
            <el-option v-for="item in commentDateTypeOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="禁止打开输出目录"
                      prop="disableOpenDir">
          <el-select v-model="temp.disableOpenDir"
                     placeholder="请选择"
                     size="small">
            <el-option v-for="item in yesOrNoOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="覆盖已生成文件"
                      prop="fileOverride">
          <el-select v-model="temp.fileOverride"
                     placeholder="请选择"
                     size="small">
            <el-option v-for="item in yesOrNoOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="开启 lombok 模式"
                      prop="swagger">
          <el-select v-model="temp.lombok"
                     placeholder="请选择"
                     size="small">
            <el-option v-for="item in yesOrNoOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="开启 swagger 模式"
                      prop="swagger">
          <el-select v-model="temp.swagger"
                     placeholder="请选择"
                     size="small">
            <el-option v-for="item in yesOrNoOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="开启 kotlin 模式"
                      prop="kotlin">
          <el-select v-model="temp.kotlin"
                     placeholder="请选择"
                     size="small">
            <el-option v-for="item in yesOrNoOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary"
                   @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible"
               title="Reading statistics">
      <el-table :data="pvData"
                border
                fit
                highlight-current-row
                style="width: 100%">
        <el-table-column prop="key"
                         label="Channel" />
        <el-table-column prop="pv"
                         label="Pv" />
      </el-table>
      <span slot="footer"
            class="dialog-footer">
        <el-button type="primary"
                   @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { page, saveOrUpdate, remove } from '@/api/global'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const calendarTypeOptions = [
  { key: 'mysql', display_name: 'mysql' },
  { key: 'oracle', display_name: 'oracle' },
  { key: 'postgresql', display_name: 'postgresql' }
]
// 是、否选项
const yesOrNoOptions = [
  { value: 1, label: '是' },
  { value: 0, label: '否' }
]
// 数据库时间类型 到 实体类时间类型 对应策略
const dateTypeOptions = [
  // 只使用 java.util.date 代替
  { value: 'ONLY_DATE', label: 'ONLY_DATE' },
  // 使用 java.sql 包下的
  { value: 'SQL_PACK', label: 'SQL_PACK' },
  //  使用 java.time 包下的 java8 新的时间类型（ 默认值）
  { value: 'TIME_PACK', label: 'TIME_PACK' }
]
// 注释日期
const commentDateTypeOptions = [
  // 只使用 java.util.date 代替
  { value: 'yyyy年MM月dd日HH时mm分ss秒', label: 'yyyy年MM月dd日HH时mm分ss秒' },
  // 使用 java.sql 包下的
  { value: 'yyyy-MM-dd HH:mm:ss', label: 'yyyy-MM-dd HH:mm:ss' },
  //  使用 java.time 包下的 java8 新的时间类型（ 默认值）
  { value: 'yyyy年MM月dd日', label: 'yyyy年MM月dd日' },
  { value: 'yyyy-MM-dd', label: 'yyyy-MM-dd' }
]
// 遍历选项，获取数字对应的字符串值
const yesOrNoTypeKeyValue = yesOrNoOptions.reduce((acc, cur) => {
  acc[cur.value] = cur.label
  return acc
}, {})
// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter (status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter (type) {
      return calendarTypeKeyValue[type]
    },
    // 是否值过滤器
    yesOrNoFilter (type) {
      return yesOrNoTypeKeyValue[type]
    }
  },
  data () {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageSize: 10,
        pageNo: 1,
        dbTypeName: undefined,
        name: undefined
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      yesOrNoOptions,
      dateTypeOptions,
      commentDateTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        name: '',
        disableOpenDir: 1,
        outputDir: 'D://',
        fileOverride: 0,
        open: '',
        dateType: 'TIME_PACK',
        swagger: 0,
        lombok: 0,
        kotlin: 0,
        commentDate: 'yyyy年MM月dd日HH时mm分ss秒',
        author: 'pearl'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        author: [{ required: true, message: '作者名不能为空', trigger: 'blur' }],
        outputDir: [{ required: true, message: '输出目录不能为空', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created () {
    this.getList()
  },
  methods: {
    getList () {
      this.listLoading = true
      page(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 200)
      })
    },
    handleFilter () {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus (row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange (data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID (order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp () {
      this.temp = {
        id: undefined,
        name: '',
        disableOpenDir: 1,
        outputDir: 'D://',
        fileOverride: 0,
        open: '',
        dateType: 'TIME_PACK',
        lombok: 0,
        swagger: 0,
        kotlin: 0,
        commentDate: 'yyyy年MM月dd日HH时mm分ss秒',
        author: 'pearl'
      }
    },
    // 处理新增确定
    handleCreate () {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          saveOrUpdate(this.temp).then(() => {
            this.dialogFormVisible = false
            page(this.listQuery).then(response => {
              this.list = response.data
              this.total = response.total
            })
            this.$notify({
              title: '提示消息',
              message: '创建成功',
              type: 'success',
              duration: 1500
            })
          })
        }
      })
    },
    // 处理修改
    handleUpdate (row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 修改数据
    updateData () {
      // 校验表单
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          saveOrUpdate(tempData).then(() => {
            page(this.listQuery).then(response => {
              this.list = response.data
              this.total = response.total
            })
            this.dialogFormVisible = false
            this.$notify({
              title: '提示消息',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 删除
    handleDelete (row, index) {
      remove(row.id).then(() => {
        page(this.listQuery).then(response => {
          this.list = response.data
          this.total = response.total
        })
        this.$notify({
          title: '提示消息',
          message: '成功删除',
          type: 'success',
          duration: 2000
        })
      })
    }
  }
}
</script>
